package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.sky.entity.Orders;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component //自定义定时任务类
public class OrderTask {

    @Autowired
    private OrderService orderService;

    //定时处理超时订单
    @Scheduled(cron = "0 * * * * ?") //每分钟触发一次
    //@Scheduled(cron = "0/5 * * * * ?") //每分钟触发一次
    public void processTimeoutOrder() {
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getStatus, Orders.PENDING_PAYMENT)
                .lt(Orders::getOrderTime, localDateTime);
        List<Orders> list = orderService.list(ordersLambdaQueryWrapper);
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(Orders::getId, orders.getId()).set(Orders::getStatus, Orders.CANCELLED)
                        .set(Orders::getCancelTime, LocalDateTime.now())
                        .set(Orders::getCancelReason, "订单超时，自动取消");
                orderService.update(lambdaUpdateWrapper);
            }
        }
    }

    //定时处理一直处于派送中状态的订单
    @Scheduled(cron = "0 0 1 * * ?") //每天凌晨一点触发一次
    public void processDeliveryOrder() {
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.eq(Orders::getStatus, Orders.DELIVERY_IN_PROGRESS)
                .lt(Orders::getCheckoutTime, localDateTime);
        List<Orders> list = orderService.list(ordersLambdaQueryWrapper);
        if (list != null && list.size() > 0) {
            for (Orders orders : list) {
                LambdaUpdateWrapper<Orders> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                lambdaUpdateWrapper.eq(Orders::getId, orders.getId()).set(Orders::getStatus, Orders.COMPLETED);
                orderService.update(lambdaUpdateWrapper);
            }
        }
    }
}
